# -*- coding:utf-8 -*-

import requests
from lxml import etree
from fake_useragent import UserAgent
from http import cookiejar
import json
from datetime import datetime
import time
import re
import csv
import base64
import random
import codecs
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import algorithms
from cryptography.hazmat.primitives.ciphers import Cipher
from cryptography.hazmat.primitives.ciphers import modes
from utils.HttpUtils import HttpUtils


requests.packages.urllib3.disable_warnings()  # 忽略HTTPS安全警告

"""
网易云音乐-评论、歌词
https://music.163.com/song?id=3060679347
"""



class Wy_Get():
    def __init__(self):
        #声明一个CookieJar对象实例来保存cookie
        # requests.utils.dict_from_cookiejar(html.cookies)  # 获取cookies转dict
        self.cookie = cookiejar.CookieJar()
        ua = UserAgent(use_cache_server=False)  # 禁用服务器缓存
        self.headers = {
            # "User-Agent": ua.random
            'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1 Safari/605.1.15',
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://music.163.com/song?id=3060679347',
        }
        self.rsa_exponent = '010001'
        self.rsa_modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7'
        self.aes_key = b'0CoJUm6Qyw8W8jud'
        self.aes_iv = b'0102030405060708'


    def get_contents(self, data, cursor, rid):
        """
        :param data: 返回加密参数
        :param cursor: 游标
        :param rid: url中的https://music.163.com/weapi/v1/resource/comments/A_PL_0_3060679347?csrf_token=
        :return:
        """
        postData = {
            'params': data['params'],
            'encSecKey': data['encSecKey']
        }
        id = rid.split("_")[3]
        self.headers['Referer'] = f"https://music.163.com/song?id={id}"

        # url = "https://music.163.com/weapi/v1/resource/comments/A_PL_0_3060679347?csrf_token="
        url = f"https://music.163.com/weapi/v1/resource/comments/{rid}?csrf_token="
        html = HttpUtils.do_request("POST", url, self.headers, postData)

        data_json = json.loads(html.text)
        # 精彩评论
        for d in data_json['comments']:
            dict_data = dict()
            dict_data['nickname'] = d['user']['userId']  # 用户id
            dict_data['nickname'] = d['user']['nickname']  # 用户名
            dict_data['content'] = d['content']  # 内容
            dict_data['time'] = datetime.fromtimestamp(d['time'] / 1000).strftime("%Y-%m-%d %H:%M:%S")  # 时间
            dict_data['likedCount'] = d['likedCount']  # 点赞数量
            print(str(dict_data))
        # 最新评论
        for d in data_json['comments']:
            dict_data = dict()
            dict_data['nickname'] = d['user']['userId']  # 用户id
            dict_data['nickname'] = d['user']['nickname']  # 用户名
            dict_data['content'] = d['content']  # 内容
            dict_data['time'] = datetime.fromtimestamp(d['time'] / 1000).strftime("%Y-%m-%d %H:%M:%S")  # 时间
            dict_data['likedCount'] = d['likedCount']  # 点赞数量
            print(str(dict_data))

    def get_lyric(self, id):
        """
        获取音乐歌词
        :param id: url中的参数id https://music.163.com/#/song?id=1427912360
        :return:
        """
        url = f"https://music.163.com/api/song/lyric?id={id}&lv=1&kv=1&tv=-1"
        html = HttpUtils.do_request("GET", url, "", "")
        data_json = json.loads(html.text)
        lyric = data_json['lrc']['lyric']

    def random_key(self):
        text = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
        key = ''
        for i in range(16):
            random_num = random.random() * len(text)
            num = int(random_num)
            key = key + text[num]
        return key

    def aes_encrypt(self, content, key):
        if not isinstance(content, bytes):
            content = content.encode()
        content += b'\x07' * (16 - len(content) % 16)
        cipher = Cipher(algorithms.AES(key), modes.CBC(self.aes_iv), backend=default_backend())
        encryptor = cipher.encryptor()
        data = encryptor.update(content)
        _data = base64.b64encode(data).decode()
        return _data

    def rsa_encrypt(self, content):
        content = content[::-1]
        rs = int(codecs.encode(content.encode('utf-8'),'hex_codec'), 16) ** int(self.rsa_exponent, 16) % int(self.rsa_modulus, 16)
        return format(rs, 'x').zfill(256)

    def encrypt(self, content):
        random_key = self.random_key()
        aes_cipher1 = self.aes_encrypt(content, self.aes_key)
        aes_cipher2 = self.aes_encrypt(aes_cipher1, random_key.encode())
        rsa_cipher = self.rsa_encrypt(random_key)

        return {'params':aes_cipher2,'encSecKey':rsa_cipher}


if __name__ == '__main__':
    wy_get = Wy_Get()
    # # 获取音乐歌词
    # wy_get.get_lyric("1427912360")

    # 获取评论内容
    rid = "A_PL_0_3060679347"
    rid = "R_SO_4_461864856"
    for i in range(0, 100, 20):
        _data = {"rid":rid,"offset":i,"total":"false","limit":"20","csrf_token":""}
        data = wy_get.encrypt(json.dumps(_data, separators=(',', ':')))
        print(f"============{i}=============")
        wy_get.get_contents(data, i, rid)
